// Copyright 2012. InMobi. All Rights reserved

package com.inmobi.sharedlock;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 *
 */
public class ThreadSafeCalculator3 implements AverageCalculator {
  
  private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(false);
  
  private final Lock read = readWriteLock.readLock();
  
  private final Lock write = readWriteLock.writeLock();

  private AtomicLong sum = new AtomicLong(0);

  private AtomicInteger count = new AtomicInteger(0);

  @Override
  public void addValue(long value) {
    read.lock();
    try {
      count.incrementAndGet();
      sum.addAndGet(value);
    } finally {
      read.unlock();
    }
  }

  @Override
  public double getAverage() {
    write.lock();
    try {
      long countValue = count.get();
      double sumValue = (double) sum.get();
      return countValue != 0 ? sumValue / countValue : 0.0;
    } finally {
      write.unlock();
    }
  }

}
